#include "player.h"
#include "sprite.h"
#include "globals.h"
#include "level.h"
#include <SDL.h>
#include <string>

Player::Player()
{

}

Player::Player(Graphics &G)
{
	VCollide = false;
	Jumping = false;
	AllowJump = false;
	VSpeed = 1;
	HSpeed = 2;
	JumpSpeed = 0;
	X = 0;
	Y = (Globals::SCREEN_HEIGHT - 156);
	LastX = X;
	LastY = Y;
	Frame = 0;
	Status = 0;
	Offset = SDL_Rect();
	CR = SDL_Rect();
	CR.x = X;
	CR.y = Y;
	CR.w = 16;
	CR.h = 24;
	SRL = SDL_RendererFlip::SDL_FLIP_NONE;
	std::string Dir = "Content/Player/Idle";
	std::string Type = ".png";
	for (int i = 0; i < 10; i++)
	{
		std::string File = Dir;
		File += std::to_string(i);
		File += Type;
		Idle.push_back(Sprite(G, File, 0, 0, 16, 24, X, Y));
	}
	Dir = "Content/Player/Run";
	for (int i = 0; i < 10; i++)
	{
		std::string File = Dir;
		File += std::to_string(i);
		File += Type;
		Run.push_back(Sprite(G, File, 0, 0, 16, 24, X, Y));
	}
}

void Player::Update(float ElapsedTime, Level &L)
{
	NoCollide = 0;
	CR.x = X;
	CR.y = Y;
	Frame += 0.15f;
	if (Frame > 9)
		Frame = 0;
	for (int i = 0; i < Idle.size(); i++)
	{
		Idle[i].X = X;
		Idle[i].Y = Y;
	}
	for (int i = 0; i < Run.size(); i++)
	{
		Run[i].X = X;
		Run[i].Y = Y;
	}
	for (int i = 0; i < L.Coins.size(); i++)
	{
		if (SDL_HasIntersection(&CR, &L.Coins[i].CR))
		{
			L.Coins.erase(L.Coins.begin() + i);
		}
	}
	for (int i = 0; i < L.Cells.size(); i++)
	{
		if (SDL_HasIntersection(&CR, &L.Cells[i].CR))
		{
			NoCollide += 1;
			X = LastX;
			if (std::floor((CR.y + CR.h) - L.Cells[i].CR.y) >= 1)
			{
				VCollide = true;
				Y = LastY;
			}
			else
				VCollide = false;
		}
	}
	LastX = X;
	LastY = Y;
	Y += VSpeed;
	if (VCollide == true)
	{
		VSpeed = 0;
	}
	else
	{
		VSpeed = 1;
	}
	if (Jumping == true)
	{
		JumpSpeed += 0.2f;
		Y += JumpSpeed;
		if (JumpSpeed >= 0)
			JumpSpeed = 0;
		if (JumpSpeed >= 0 && NoCollide != 0)
			Jumping = false;
	}
	if (VSpeed == 0 && NoCollide == 0)
		VSpeed = 1;
}

void Player::Draw(Graphics &G)
{
	if (Status == 0)
		Idle[std::floor(Frame)].Draw(G, SRL);
	if (Status == 1)
		Run[std::floor(Frame)].Draw(G, SRL);
	if (Status == -1)
		Run[std::floor(Frame)].Draw(G, SRL);
}

void Player::Still()
{
	Status = 0;
}

void Player::MoveRight()
{
	X += HSpeed;
	Status = 1;
	SRL = SDL_RendererFlip::SDL_FLIP_NONE;
}

void Player::MoveLeft()
{
	X -= HSpeed;
	Status = -1;
	SRL = SDL_RendererFlip::SDL_FLIP_HORIZONTAL;
}

void Player::Jump()
{
	if (Jumping == false)
	{
		JumpSpeed = -5;
		Jumping = true;
	}
}